package com.ocom.oauth.auth.web;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import com.ocom.oauth.auth.CustomAbstractTokenGranter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 *
 *  说明：
 *    验证码
 *    定义验证码具体逻辑
 */
public class CodeTokenGranter extends CustomAbstractTokenGranter {

    private static final String CODE_AUTH = "code_auth";

    private final CustomUserDetailService customUserDetailService;

    public CodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, CustomUserDetailService  customUserDetailService) {
        super(tokenServices, clientDetailsService, requestFactory, CODE_AUTH);
        this.customUserDetailService = customUserDetailService;
    }

    @Override
    protected UserDetails getUserDetails(Map<String, String> parameters) {
//        String username = parameters.get("username");
//        String smsCode = parameters.get("sms_code");
//        String password = parameters.get("password");
        String key = "tbk0Xa67cEePvv14g5Pf1MPzIceQMN14"; // 密钥（8 字节）
        String username = HexUtil.decodeHexStr(parameters.get("username"));
        String smsCode = parameters.get("sms_code");
        String password = HexUtil.decodeHexStr(parameters.get("password"));
        username = SecureUtil.des(key.getBytes(StandardCharsets.UTF_8)).decryptStr(username);
        password = SecureUtil.des(key.getBytes(StandardCharsets.UTF_8)).decryptStr(password);
        String from = parameters.get("from");
        return customUserDetailService.loadByNameAndCode(username,password,smsCode,from);
    }
}
